﻿using System;
using System.Linq;
using System.Threading;
using System.Diagnostics.Tracing;
using System.IO;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Diagnostics;

namespace CNI.NRT.WebAPI
{
    public static class Logger
    {
        static TemperatureEventSource log;
        static TemperatureEventListener listener;

        private static string Path { set; get; }

        static public void Start(string path)
        {
            Path = path;

            log = TemperatureEventSource.Logger;

            listener = new TemperatureEventListener(path);
            listener.EnableEvents(log, EventLevel.LogAlways);
        }

        public static void LogTemperatureData(string jsonData)
        {
            log.LogString(jsonData);
        }

        public static void Dispose()
        {
            listener.Dispose();
        }

    }
    sealed public class TemperatureEventSource : EventSource
    {

        [Event(1, Message = "{0}", Level = EventLevel.LogAlways)]
        public void LogString(string tel)
        {
            WriteEvent(1, tel);
        }

        public static TemperatureEventSource Logger = new TemperatureEventSource();

    }

    public class TemperatureEventListener : EventListener
    {

        string rootPath = null;
        int numEvents = 0;
        int numEventGroups = 1;
        StreamWriter stream = null;
        string InstanceID = null;
        const int MAXEVENTS = 1000;

        public TemperatureEventListener(string path)
        {
            rootPath = path;
            string temp = RoleEnvironment.CurrentRoleInstance.Id;
            InstanceID = temp.Split('.').Last();

            stream = NewStream();
        }

        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            numEvents++;

            Monitor.Enter(stream);
            try
            {
                if (eventData.EventId == 1)
                    stream.WriteLine(string.Format(eventData.Message, eventData.Payload[0]));

                if (numEvents > MAXEVENTS)
                {
                    stream.Flush();
                    stream.Close();
                    stream = NewStream();
                    numEvents = 0;
                    numEventGroups++;
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception calling OnEventWritten: {0}", ex.Message);
            }
            finally
            {
                Monitor.Exit(stream);
            }

        }

        StreamWriter NewStream()
        {

            string directory = Path.Combine(rootPath, "Logs");
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            string filePath = Path.Combine(directory, String.Format("{1}-Temperature-{0}.txt", DateTime.Now.Ticks, InstanceID));
            numEvents = 0;

            return new StreamWriter(filePath, true, System.Text.Encoding.UTF8, 10000);
        }

        public override void Dispose()
        {
            Trace.TraceInformation("TemperatureEventListener:Dispose - dispose was called.");

            if (stream != null)
            {
                stream.Flush();
                stream.Close();
                stream = null;
            }
            base.Dispose();
        }

    }
}
